import Hapi from "@hapi/hapi";
import Boom from "@hapi/boom";
import fs from "fs-extra";
import { uploadSchema } from "./schema/index";
const route: Hapi.ServerRoute<Hapi.ReqRefDefaults> = {
  method: "post",
  path: "/upload",
  options: {
    payload: {
      parse: true,
      multipart: {
        output: "stream",
      },
      allow: "multipart/form-data",
      maxBytes: 100 * 1024 * 1024, // Maximum file size is 100MB
    },
    tags: ["api"],
    validate: { payload: uploadSchema },
    plugins: {
      "hapi-swagger": {
        // 在 hapi-swagger 中设置 allowFormats 选项允许上传文件
        allowFormats: ["multipart/form-data"],
      },
    },
    auth: false,
  },
  handler: async (request, h) => {
    let { file, filePath } = request.payload as any;
    if (!filePath) {
      filePath = "default";
    }
    if (!file) {
      throw Boom.badRequest("File is missing");
    }
    const filename = file.hapi.filename;
    const data = file._data;
    const path = getFilename(filename);
    fs.ensureDir(`./public/${filePath}`);
    fs.writeFileSync(`./public/${filePath}/${path}`, data);
    const NODE_ENV = process.env.NODE_ENV;
    const baseUrl =
      NODE_ENV == "dev"
        ? `http://localhost:7070/${filePath}/`
        : `https://www.yoge.fun/api/${filePath}/`;
    return `${baseUrl}${path}`;
  },
};
export default route;

const getFilename = (filename: string) => {
  return Date.now() + Math.floor(Math.random() * 10000) + filename;
};
